package cn.yuanqiao.archive.webservice.utils;

import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import org.mozilla.universalchardet.UniversalDetector;

import java.io.*;

public class XMLtoJsonUtils {

    /**
     * 自定义*/
    public static JSONObject startXMLToJSON(File path) throws Exception{
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(path))) {
            UniversalDetector detector = new UniversalDetector(null);
            byte[] buf = new byte[4096];
            int nread;

            while ((nread = bis.read(buf)) > 0 && !detector.isDone()) {
                detector.handleData(buf, 0, nread);
            }

            detector.dataEnd();
            //读取txt文件的编码格式
            String encoding = detector.getDetectedCharset();
            detector.reset();
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(path), encoding))) {
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                    sb.append(System.lineSeparator());
                }
                String xml = sb.toString();
                XmlMapper xmlMapper = new XmlMapper();
                ObjectMapper objectMapper = new ObjectMapper();
                Object xmlObject = xmlMapper.readValue(xml, Object.class);
                return JSONObject.parseObject(objectMapper.writeValueAsString(xmlObject));
            }
        }
    }
}
